<template>
  <view
    class="content"
    :style="{
      backgroundImage: `url(${getImageUrl('user-bg.png')})`,
      backgroundSize: `100% ${statusBarHeight + 200}px`
    }"
    style="background-repeat: no-repeat; background-position: top"
  >
    <view class="">
      <view class="u-navbar" :style="[navbarStyle]">
        <view class="u-status-bar" :style="{ height: statusBarHeight + 'px' }"></view>
        <view class="u-navbar-inner" :style="[navbarInnerStyle]">
          <view class="u-navbar-content-title">
            <!-- #ifdef MP -->
            <view class="u-title left"> 我的</view>
            <!-- #endif -->
            <!-- #ifndef MP -->
            <view class="u-title center"> 我的</view>
            <!-- #endif -->
          </view>
        </view>
      </view>
    </view>
    <view class="contentView">
      <view class="headerView dis-flex flex-x-center flex-y-center" @longpress="handleLongPress">
        <view v-if="userInfo" class="userView flex-1">
          <u-avatar
            @click.native.stop.prevent="routeTo('/users/info')"
            :src="userInfo.avatar"
            size="120"
            mode="circle"
          ></u-avatar>
          <view class="userInfo">
            <view class="username" @click.stop.prevent="routeTo('/users/info')"
              >{{ userInfo.nickname }}
            </view>
            <view style="display: flex">
              <view
                v-if="userInfo.isMerchant"
                class="userType"
                @click.stop.prevent="routeTo('/users/svip')"
              >
                <text v-if="userInfo.isMerchantVip">VIP商家</text>
                <text v-else>普通商家</text>
              </view>
              <view v-else class="userType" @click.stop.prevent="routeTo('/users/svip')">
                <text v-if="userInfo.isVip">VIP用户</text>
                <text v-else>普通用户</text>
              </view>
            </view>
          </view>
        </view>
        <view v-else class="userView flex-1" @click.stop.prevent="onLogin()">
          <u-avatar src="@/static/d-avatar.png" size="120" mode="circle"></u-avatar>
          <view class="userInfo">
            <view class="logoBtn">登录后使用更多功能</view>
            <text class="logo-btn"> 立即登录</text>
          </view>
        </view>
        <view
          v-if="userInfo"
          class="myTeam dis-flex flex-column flex-x-center flex-y-center"
          @click.stop.prevent="onTeams()"
        >
          <view class="teamNumber">
            {{
              userCount ? userCount.inviteDirectCount + userCount.inviteIndirectCount + '人' : '--'
            }}
          </view>
          <view class="teamName">我的团队</view>
        </view>
      </view>

      <view class="blockView orderView">
        <!-- <view class="orderTab">
          <view class="activeTab flag">我的订单</view>
          <view class="otherText" @click="onGoodsOrder('')">
            <text style="margin-right: 8rpx">更多</text>
            <u-icon name="/static/more.png" size="14"></u-icon>
          </view>
        </view> -->
        <view class="tabItemView">
          <view
            class="tabItem"
            style="position: relative"
            v-for="(type, key) in orderTypes"
            :key="key"
            @click="onGoodsOrder(type.key)"
          >
            <u-icon :name="type.iconUrl" size="48rpx"></u-icon>
            <view class="tabTitle">{{ type.name }}</view>
            <u-badge type="error" size="mini" :count="type.count"></u-badge>
          </view>
        </view>
      </view>

      <view class="blockView orderView amount">
        <view class="tabItemView">
          <view class="tabItem" @click="onMyGift()">
            <view class="tabNumber">{{ userCount ? userCount.giftUnusedCount : '--' }}</view>
            <view class="tabTitle2">赠品券</view>
          </view>
          <view class="tabItem" @click="onMyCoupon()">
            <view class="tabNumber">{{ userCount ? userCount.couponUnusedCount : '--' }}</view>
            <view class="tabTitle2">优惠券</view>
          </view>
          <view class="tabItem" @click="onMyIntegral()">
            <view class="tabNumber">{{ userCount ? userCount.totalPoint : '--' }}</view>
            <view class="tabTitle2">积分</view>
          </view>
          <view class="tabItem" @click="onRedPacket()">
            <view class="tabNumber">{{ computedRedPacket }}</view>
            <view class="tabTitle2">红包</view>
          </view>
          <view class="tabItem" @click="onWallet()">
            <view class="tabNumber">{{ computedBalance }}</view>
            <view class="tabTitle2">余额</view>
          </view>
        </view>
      </view>

      <view
        v-if="userInfo && userInfo.isRider"
        class="blockView rider"
        @click="routeTo('/rider/order-list/order-list')"
      >
        <u-image src="/static/rider/rider_menu.png" width="90rpx" height="90rpx"></u-image>
        <view class="rider-des">
          <text class="rider-des-t">配送员中心</text>
          <text class="rider-des-c">配送轻松、赚钱自由</text>
        </view>
        <view v-if="riderOrderCount > 0" class="rig-tip dis-flex flex-x-baseline">
          <text>有</text>
          <text style="color: red; font-weight: bold">{{ riderOrderCount }}笔</text>
          <text>订单待处理</text>
        </view>
        <view v-else-if="riderStatusLoading" class="rig-tip dis-flex flex-x-baseline">
          <text>进入管理</text>
        </view>
        <view
          v-else
          class="dis-flex flex-column flex-y-center"
          @click.stop.prevent="changeRiderResting"
        >
          <u-switch
            v-model="riderNotResting"
            size="30"
            :disabled="riderStatusLoading"
            :loading="riderStatusLoading"
          />
          <text class="rig-tip" :style="riderNotResting ? 'color: #10a28f' : 'color: #999999'">{{
            riderNotResting ? '接单中' : '休息中'
          }}</text>
        </view>
      </view>

      <view
        v-if="applyList && applyList.length > 0"
        class="blockView apply dis-flex flex-y-between"
      >
        <view
          class="dis-flex flex-y-between flex-y-center"
          @click="routeTo(apply.linkUrl)"
          v-for="(apply, a) in applyList"
          :key="a"
        >
          <u-image :src="apply.picUrl" width="90rpx" height="90rpx"></u-image>
          <view class="apply-des">
            <view class="a-d-t">{{ apply.title }}</view>
            <view class="a-d-c">{{ apply.subTitle }}</view>
          </view>
        </view>
      </view>

      <view
        v-if="menuList3 && menuList3.length > 0"
        class="blockView amount dis-flex flex-y-between"
      >
        <view v-for="(img, i) in menuList3" :key="i" style="width: 100%">
          <u-image
            @click="allianceMenu(img, false)"
            :src="img.picUrl"
            width="100%"
            height="180rpx"
            border-radius="10rpx 10rpx 0 0"
          ></u-image>
        </view>
      </view>

      <!-- <view v-if="menuList4 && menuList4.length > 0" class="blockView orderView tabItemView">
        <view
          class="blockItem tabItem"
          style="position: relative"
          v-for="(item, index) in menuList4"
          :key="index"
          @click="allianceMenu(item, false)"
        >
          <view class="gridView">
            <u-image :src="item.picUrl" width="80rpx" height="80rpx"></u-image>
            <view class="gridText">{{ item.title }}</view>
            <view class="a-d-c" style="margin-top: 4rpx">{{ item.number ? item.number : 0 }}</view>
          </view>
        </view>
      </view> -->

      <view v-if="menuList2 && menuList2.length > 0" class="blockView orderView tabItemView">
        <view
          class="blockItem tabItem"
          style="position: relative"
          v-for="(item, index) in menuList2"
          :key="index"
          @click="onPathPage1(item)"
        >
          <view class="gridView">
            <u-image :src="item.picUrl" width="44rpx" height="44rpx"></u-image>
            <view class="gridText">{{ item.title }}</view>
          </view>
        </view>
      </view>

      <u-gap height="80" bg-color=""></u-gap>
    </view>
    <UFoooter ref="uTab"></UFoooter>
  </view>
</template>

<script>
// 获取系统状态栏的高度
let systemInfo = uni.getSystemInfoSync()
let menuButtonInfo = {}
// 如果是小程序，获取右上角胶囊的尺寸信息，避免导航栏右侧内容与胶囊重叠(支付宝小程序非本API，尚未兼容)
// #ifdef MP-WEIXIN || MP-BAIDU || MP-TOUTIAO || MP-QQ
menuButtonInfo = uni.getMenuButtonBoundingClientRect()
// #endif
import UFoooter from '@/components/uTabbar.vue'

export default {
  components: {
    UFoooter
  },
  data() {
    return {
      orderTypes: [
        // {
        //   name: '待付款',
        //   iconUrl: '/static/dfk.png',
        //   key: 'payment',
        //   count: 0
        // },
        {
          name: '扫码订单',
          iconUrl: '/static/dfk.png',
          key: 'scan_order',
          count: 0
        },
        {
          name: '交易订单',
          iconUrl: '/static/dsd.png',
          key: 'trade_order',
          count: 0
        },
        // {
        //   name: '待发货',
        //   iconUrl: '/static/dsd.png',
        //   key: 'deliver',
        //   count: 0
        // },
        // {
        //   name: '待收货',
        //   iconUrl: '/static/dsh.png',
        //   key: 'receive',
        //   count: 0
        // },
        // {
        //   name: '待核销',
        //   iconUrl: '/static/dsy.png',
        //   key: 'clerk',
        //   count: 0
        // },
        {
          name: '退款/售后',
          iconUrl: '/static/thh.png',
          key: 'return',
          count: 0
        }
      ],
      menuButtonInfo: menuButtonInfo,
      statusBarHeight: systemInfo.statusBarHeight,
      height: '',
      titleWidth: '',
      navBackground: {
        background: '#000000'
      },
      userCount: null,
      userInfo: null,
      riderOrderCount: 0,
      riderNotResting: true,
      riderStatusLoading: true,
      userCode: '',
      couponCount: 0,
      menuList: [],
      menuList2: [],
      menuList3: [],
      //menuList4: [],
      applyList: []
    }
  },
  onShow() {
    this.userInfo = uni.getStorageSync('userInfo')
    this.refreshData()
  },
  onPullDownRefresh() {
    this.refreshData()
    setTimeout(() => {
      uni.stopPullDownRefresh()
    }, 1500)
  },
  onShareAppMessage() {
    return {
      path: '/pages/index/index?pid=' + this.userCode
    }
  },
  computed: {
    // 导航栏内部盒子的样式
    navbarInnerStyle() {
      let style = {}
      // 导航栏宽度，如果在小程序下，导航栏宽度为胶囊的左边到屏幕左边的距离
      style.height = this.navbarHeight + 'px'
      // // 如果是各家小程序，导航栏内部的宽度需要减少右边胶囊的宽度
      // #ifdef MP
      let rightButtonWidth = systemInfo.windowWidth - menuButtonInfo.left
      style.marginRight = rightButtonWidth + 'px'
      // #endif
      return style
    },
    // 整个导航栏的样式
    navbarStyle() {
      let style = {}
      // style.zIndex = this.zIndex ? this.zIndex : this.$u.zIndex.navbar;
      // 合并用户传递的背景色对象
      Object.assign(style, this.background)
      return style
    },
    // 导航中间的标题的样式
    titleStyle() {
      let style = {}
      // #ifndef MP
      style.left = (systemInfo.windowWidth - uni.upx2px(this.titleWidth)) / 2 + 'px'
      style.right = (systemInfo.windowWidth - uni.upx2px(this.titleWidth)) / 2 + 'px'
      // #endif
      // #ifdef MP
      // 此处是为了让标题显示区域即使在小程序有右侧胶囊的情况下也能处于屏幕的中间，是通过绝对定位实现的
      let rightButtonWidth = systemInfo.windowWidth - menuButtonInfo.left
      style.left = (systemInfo.windowWidth - uni.upx2px(this.titleWidth)) / 2 + 'px'
      style.right =
        rightButtonWidth -
        (systemInfo.windowWidth - uni.upx2px(this.titleWidth)) / 2 +
        rightButtonWidth +
        'px'
      // #endif
      style.width = uni.upx2px(this.titleWidth) + 'px'
      return style
    },
    // 转换字符数值为真正的数值
    navbarHeight() {
      let h
      // #ifdef APP-PLUS || H5
      h = this.height ? this.height : 44
      // #endif
      // #ifdef MP
      // 小程序特别处理，让导航栏高度 = 胶囊高度 + 两倍胶囊顶部与状态栏底部的距离之差(相当于同时获得了导航栏底部与胶囊底部的距离)
      // 此方法有缺陷，暂不用(会导致少了几个px)，采用直接固定值的方式
      // return menuButtonInfo.height + (menuButtonInfo.top - this.statusBarHeight) * 2;//导航高度
      let height = systemInfo.platform == 'ios' ? 44 : 48
      h = this.height ? this.height : height
      // #endif
      return h
    },
    computedRedPacket() {
      if (!this.userCount) {
        return '--'
      }
      if (!this.userCount.shopRedPacketAmount) {
        return 0
      }
      const count =
        (this.userCount.shopRedPacketAmount.unusedAmount + this.userCount.platformRedPacketAmount) *
        0.01
      return parseInt(count)
    },
    computedBalance() {
      if (!this.userCount) {
        return '--'
      }
      if (!this.userCount.totalBalance) {
        return 0
      }
      const count = this.userCount.totalBalance * 0.01
      return count < 10 ? count.toFixed(2) : parseInt(count)
    }
  },
  methods: {
    handleLongPress() {
      // 注;为方便小程序环境登录测试，长按退出跳转到通用的登录页，而不是小程序一键登录页
      this.$utils.handleLogout(() => {
        uni.redirectTo({
          url: '/universal/login/login'
        })
      })
    },
    refreshData() {
      const app = this
      app.getMenus()
      app.getUserCount()
      if (app.userInfo) {
        app.refreshUserInfo()
        app.getOrderCount()
        if (app.userInfo.isRider) {
          app.getRiderOrderCount()
          app.getRiderResting()
        }
        if (app.$refs.uTab) {
          app.$refs.uTab.setCartTabBadge()
        }
      } else {
        app.userInfo = null
        const newOrderNavbar = []
        app.orderTypes.forEach((item) => {
          item.count = 0
          newOrderNavbar.push(item)
        })
        app.orderTypes = newOrderNavbar
      }
    },
    allianceMenu(item, checkAbility = true) {
      if (!this.userInfo) {
        this.onLogin()
        return
      }
      if (!checkAbility || this.userInfo.isCloudAlliance) {
        if (item && item.linkUrl && item.linkUrl.length > 1) {
          this.$utils.route(item.linkUrl)
          return
        }
        if (item && item.subIdentify) {
          if (item.subIdentify == 'lianmengdou') {
            this.$utils.route('/alliance/beans')
            return
          }
          if (item.subIdentify == 'shouyidou') {
            this.$utils.route('/alliance/shouyidou')
            return
          }
          if (item.subIdentify == 'fenhongdou') {
            this.$utils.route('/alliance/dillery')
            return
          }
          if (item.subIdentify == 'gongyixunzhang') {
            this.$u.toast('敬请期待！')
            return
          }
        }
        this.$utils.route('/alliance/user')
        return
      }
      this.$u.get('/app-api/member/cloud-alliance-apply/check').then((res) => {
        if (res.data.step != 0) {
          this.$utils.route('/alliance/apply-join')
        } else {
          this.$utils.route('/alliance/guide')
        }
      })
    },
    refreshUserInfo() {
      const app = this
      app.$u.api.getUserInfo().then((res) => {
        app.userInfo = res.data
        uni.setStorageSync('userInfo', res.data)
      })
    },
    getMenus() {
      this.$u.get('/app-api/cms/qlink/list?identify=mine_apply_menu').then((res) => {
        this.applyList = res.data
      })
      this.$u.get('/app-api/cms/qlink/list?identify=mine_middle_menu').then((res) => {
        this.menuList = res.data
      })
      this.$u.get('/app-api/cms/qlink/list?identify=mine_bottom_menu').then((res) => {
        this.menuList2 = res.data
      })
      this.$u.get('/app-api/cms/qlink/list?identify=mine_union_menu').then((res) => {
        this.menuList3 = res.data
      })
      // this.$u.get('/app-api/member/digital-assets/get-menu').then((res) => {
      //   this.menuList4 = res.data
      // })
    },
    getUserCount() {
      this.$u.get('/app-api/member/statistics/center-count').then((res) => {
        this.userCount = res.data
      })
    },
    getOrderCount() {
      const app = this
      app.$u.get('/app-api/trade/order/get-count').then((res) => {
        const newOrderNavbar = []
        app.orderTypes.forEach((item) => {
          if (item.key == 'payment') {
            item.count = res.data['unpaidCount']
          }
          if (item.key == 'deliver') {
            item.count = res.data['undeliveredCount']
          }
          if (item.key == 'receive') {
            item.count = res.data['deliveredCount']
          }
          if (item.key == 'clerk') {
            item.count = res.data['unusedCount']
          }
          if (item.key == 'return') {
            item.count = res.data['afterSaleCount']
          }
          if (item.key == 'trade_order') {
            item.count =
              res.data['unpaidCount'] +
              res.data['undeliveredCount'] +
              res.data['deliveredCount'] +
              res.data['unusedCount']
          }
          newOrderNavbar.push(item)
        })
        app.orderTypes = newOrderNavbar
      })
    },
    getRiderOrderCount() {
      this.$u.get('/app-api/trade/order/get-count-rider').then((res) => {
        this.riderOrderCount = res.data.doingCount
      })
    },
    getRiderResting() {
      this.riderStatusLoading = true
      this.$u
        .get('/app-api/shop/staff/get-status')
        .then((res) => {
          this.riderStatusLoading = false
          this.riderNotResting = Number(res.data) !== 2
        })
        .catch(() => {
          this.riderStatusLoading = false
        })
    },
    changeRiderResting() {
      this.riderStatusLoading = true
      this.$u
        .post('/app-api/shop/staff/update-status', { resting: !this.riderNotResting })
        .then(() => {
          this.riderStatusLoading = false
          this.getRiderResting()
        })
        .catch(() => {
          this.riderStatusLoading = false
        })
    },
    onLogin() {
      this.$utils.goToLogin()
    },
    onSetting() {
      this.$utils.route('/universal/setting/setting', false)
    },
    onGoodsOrder(key) {
      if (!this.userInfo) {
        this.onLogin()
        return
      }
      if (key === 'scan_order') {
        this.$utils.route({
          url: '/dine/scan/order'
        })
        return
      }
      if (key === 'trade_order') {
        key = ''
      }
      this.$utils.route(
        {
          url: '/goods/order-list/order-list',
          params: {
            status: key
          }
        },
        false
      )
    },
    onWallet() {
      if (!this.userInfo) {
        this.onLogin()
        return
      }
      this.$utils.route('/other/my-wallet/my-wallet', false)
    },
    onMyCoupon() {
      if (!this.userInfo) {
        this.onLogin()
        return
      }
      this.$utils.route('/other/my-coupon/my-coupon', false)
    },
    onMyGift() {
      if (!this.userInfo) {
        this.onLogin()
        return
      }
      this.$utils.route('/other/my-coupon/my-gift', false)
    },
    onRedPacket() {
      if (!this.userInfo) {
        this.onLogin()
        return
      }
      this.$utils.route('/other/my-coupon/my-red-packet', false)
    },
    onMyIntegral() {
      if (!this.userInfo) {
        this.onLogin()
        return
      }
      this.$utils.route('/other/integral/integral?count=' + this.userCount.totalPoint, false)
    },
    onTeams() {
      if (!this.userInfo) {
        this.onLogin()
        return
      }
      this.$utils.route('/users/teams/index', false)
    },
    onPathPage(item) {
      if (!this.userInfo) {
        this.onLogin()
        return
      }
      this.$utils.route(item.linkUrl, false)
    },
    onPathPage1(item) {
      let path = item.linkUrl
      if (
        !this.userInfo &&
        (path == '/users/info' ||
          path == '/other/address-manage/address-manage' ||
          path == '/users/job/index' ||
          path == '/users/star' ||
          path == '/other/my-interaction/my-interaction')
      ) {
        this.onLogin()
        return
      }
      this.$utils.route(path, false)
    },
    routeTo(url, e) {
      if (!this.userInfo) {
        this.onLogin()
        return
      }
      if (e) {
        uni.switchTab({
          url
        })
        return
      }
      if (url == '/other/apply_join_zs/apply_join') {
        if (this.userInfo.isAgency) {
          url = '/attract/index'
        }
      }
      if (url == '/other/apply_join/apply_join') {
        if (this.userInfo.isMerchant) {
          url = '/store/index'
        }
      }
      this.$utils.route(url, false)
    },
    onMyResale() {
      if (!this.userInfo) {
        this.onLogin()
        return
      }
      if (this.userInfo.isSalesman) {
        uni.navigateTo({
          url: '/other_center/salesman-invite/salesman-invite'
        })
        return
      }
      uni.navigateTo({
        url: '/other/invite-reward/invite-reward?status=1'
      })
    },
    routeToMsg() {
      uni.navigateTo({
        url: '/other_center/mer-message/mer-message'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.u-navbar-content-title {
  font-weight: 400;
  font-size: 36rpx;
  color: #fff;
  position: absolute;
  left: 20rpx;
  right: 0;
  height: 60rpx;
  line-height: 80rpx;
}

.u-title.left {
  text-align: left;
}

.u-title.center {
  text-align: center;
}

@import url('ucenter.css');

.amount {
  height: 180rpx;
  margin-left: 20rpx;
  margin-right: 20rpx;
  margin-top: 20rpx;
}

.apply {
  height: 180rpx;
  background: #ffffff;
  border-radius: 10rpx;
  margin-left: 20rpx;
  margin-right: 20rpx;
  margin-top: 20rpx;
  padding: 40rpx 64rpx;

  .apply-des {
    margin-left: 18rpx;

    .a-d-t {
      font-size: 28rpx;
    }

    .a-d-c {
      color: #999999;
      font-size: 22rpx;
    }
  }
}
</style>
